<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="物料编码" prop="materialId">
              <material-input v-model="queryParams.materialId" v-model:name="queryParams.materialCode" placeholder="请选择物料编码"></material-input>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <supplier-input v-model="queryParams.supplierId" v-model:name="queryParams.supplierName" placeholder="请选择供应商"></supplier-input>
            </el-form-item>
            <el-form-item label="质检方式" prop="quantityTestingMethod">
              <el-select v-model="queryParams.quantityTestingMethod" placeholder="请选择质检方式" clearable>
                <el-option v-for="dict in quantity_testing_method" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="包装来源" prop="source">
              <el-select v-model="queryParams.source" placeholder="请选择包装来源" clearable>
                <el-option v-for="dict in package_source" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['material:materialSupplierRel:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['material:materialSupplierRel:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['material:materialSupplierRel:remove']"
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['material:materialSupplierRel:export']" type="warning" plain icon="Download" @click="handleExport"-->
          <!--              >导出-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="materialSupplierRelList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="" align="center" prop="id" />
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="供应商" align="center" prop="supplierName" />
        <el-table-column label="质检方式" align="center" prop="quantityTestingMethod">
          <template #default="scope">
            {{ quantity_testing_method.find((item) => item.value === scope.row.quantityTestingMethod)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="质检比例" align="center" prop="quantityTestingRate" />
        <el-table-column label="包装来源" align="center" prop="source">
          <template #default="scope">
            {{ package_source.find((item) => item.value === scope.row.source)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="采购价格" align="center" prop="purchasePrice" />
        <el-table-column label="最小起订量" align="center" prop="minOrderQuantity" />
        <el-table-column label="毛重" align="center" prop="grossWeight" />
        <el-table-column label="净重" align="center" prop="netWeight" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-hasPermi="['material:materialSupplierRel:edit']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['material:materialSupplierRel:remove']"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改物料编码和供应商映射对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-form ref="materialSupplierRelFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <supplier-input v-model="form.supplierId" v-model:name="form.supplierName" placeholder="请选择供应商"></supplier-input>
            </el-form-item>
            <el-form-item label="质检方式" prop="quantityTestingMethod">
              <el-select v-model="form.quantityTestingMethod" placeholder="请选择质检方式" clearable>
                <el-option v-for="dict in quantity_testing_method" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最小起订量" prop="minOrderQuantity">
              <el-input v-model="form.minOrderQuantity" placeholder="请输入最小起订量" />
            </el-form-item>
            <el-form-item label="毛重(g)" prop="grossWeight">
              <el-input v-model="form.grossWeight" placeholder="请输入毛重" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购价格" prop="purchasePrice">
              <el-input v-model="form.purchasePrice" placeholder="请输入采购价格" />
            </el-form-item>
            <el-form-item label="质检比例" prop="quantityTestingRate">
              <el-input v-model="form.quantityTestingRate" placeholder="请输入质检比例" />
            </el-form-item>
            <el-form-item label="净重(g)" prop="netWeight">
              <el-input v-model="form.netWeight" placeholder="请输入净重" />
            </el-form-item>
            <el-form-item label="包装来源" prop="source">
              <el-select v-model="form.source" placeholder="请选择包装来源" clearable>
                <el-option v-for="dict in package_source" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MaterialSupplierRel" lang="ts">
import {
  listMaterialSupplierRel,
  getMaterialSupplierRel,
  delMaterialSupplierRel,
  addMaterialSupplierRel,
  updateMaterialSupplierRel
} from '@/api/material/materialSupplierRel';
import { MaterialSupplierRelVO, MaterialSupplierRelQuery, MaterialSupplierRelForm } from '@/api/material/materialSupplierRel/types';
import { getMaterial } from '@/api/material/material';

import { RouteLocationNormalized } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { quantity_testing_method, package_source } = toRefs<any>(proxy?.useDict('quantity_testing_method', 'package_source'));
const route = useRoute();
const materialSupplierRelList = ref<MaterialSupplierRelVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const defaultMaterialId = ref('');
const defaultMaterialCode = ref('');

const queryFormRef = ref<ElFormInstance>();
const materialSupplierRelFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MaterialSupplierRelForm = {
  id: undefined,
  materialId: undefined,
  supplierId: undefined,
  quantityTestingMethod: undefined,
  quantityTestingRate: undefined,
  purchasePrice: undefined,
  minOrderQuantity: undefined,
  grossWeight: undefined,
  netWeight: undefined,
  source: undefined,
  remark: undefined
};
const data = reactive<PageData<MaterialSupplierRelForm, MaterialSupplierRelQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialId: undefined,
    materialCode: undefined,
    supplierId: undefined,
    quantityTestingMethod: undefined,
    quantityTestingRate: undefined,
    purchasePrice: undefined,
    minOrderQuantity: undefined,
    grossWeight: undefined,
    netWeight: undefined,
    source: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    materialId: [{ required: true, message: '物料编码Id不能为空', trigger: 'blur' }],
    supplierId: [{ required: true, message: '供应商Id不能为空', trigger: 'blur' }],
    quantityTestingMethod: [{ required: true, message: '质检方式不能为空', trigger: 'blur' }],
    quantityTestingRate: [{ required: true, message: '质检比例不能为空', trigger: 'blur' }],
    purchasePrice: [{ required: true, message: '采购价格不能为空', trigger: 'blur' }],
    minOrderQuantity: [{ required: true, message: '最小起订量不能为空', trigger: 'blur' }],
    grossWeight: [{ required: true, message: '毛重不能为空', trigger: 'blur' }],
    netWeight: [{ required: true, message: '净重不能为空', trigger: 'blur' }],
    source: [{ required: true, message: '来源不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物料编码和供应商映射列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.materialId = route.params.materialId as string;
  const res = await listMaterialSupplierRel(queryParams.value);
  materialSupplierRelList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  materialSupplierRelFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.materialId = defaultMaterialId.value;
  queryParams.value.materialCode = defaultMaterialCode.value;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MaterialSupplierRelVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.materialId = defaultMaterialId.value;
  dialog.visible = true;
  dialog.title = '添加物料编码和供应商映射';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MaterialSupplierRelVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMaterialSupplierRel(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改物料编码和供应商映射';
};

/** 提交按钮 */
const submitForm = () => {
  materialSupplierRelFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMaterialSupplierRel(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMaterialSupplierRel(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MaterialSupplierRelVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除物料编码和供应商映射编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMaterialSupplierRel(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'material/materialSupplierRel/export',
    {
      ...queryParams.value
    },
    `materialSupplierRel_${new Date().getTime()}.xlsx`
  );
};

/** 返回按钮操作 */
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/material/material'
  };
  proxy?.$tab.closeOpenPage(obj);
};

/** 查询字典类型详细 */
const getDefaultMaterial = async (materialId: string | number) => {
  const { data } = await getMaterial(materialId);
  queryParams.value.materialCode = data.materialCode;
  defaultMaterialId.value = data.id + '';
  defaultMaterialCode.value = data.materialCode;
};

onMounted(() => {
  getDefaultMaterial(route.params.materialId as string);
  getList();
});
</script>
